<?php
/**
 * Created by PhpStorm.
 * User: longli
 * Date: 2020/09/14
 * Time: 17:06
 * @link http://www.lmterp.cn
 */

namespace app\common\service\product;


use app\common\library\Tools;
use app\common\model\ProductStore;
use app\common\model\Warehouse;
use app\common\model\WarehouseStock;
use app\common\service\BaseService;

class WarehouseService extends BaseService
{
    /**
     * 添加仓库
     * @param array $data 仓库信息
     * @return Warehouse|bool
     * @date 2020/09/18
     * @author longli
     */
    public function addWarehouse($data = [])
    {
        $wData = Warehouse::getFilterField($data);
        if(empty($wData)) return false;
        $wData = Tools::trim($wData);
        $w = null;
        if(isset($wData['warehouse_id'])) $w = Warehouse::get($wData['warehouse_id']);
        if(!empty($w))
        {
            $w->save($wData);
        }
        else
        {
            $w = Warehouse::create($wData);
        }
        return $w;
    }
    /**
     * 添加商品库存
     * @param int $storeId 变体 id
     * @param array $data 库存信息
     * @return WarehouseStock|bool
     * @date 2020/09/16
     * @author longli
     */
    public function addStock($storeId, $data = [])
    {
        $sData = WarehouseStock::getFilterField($data);
        if(empty($sData)) return false;
        $sData = Tools::trim($sData);
        $sData['store_id'] = $storeId;
        $sData['sku'] = ProductStore::get($storeId)->sku;
        $stock = null;
        if(isset($sData['stock_id'])) $stock = WarehouseStock::get($sData['stock_id']);
        if(!empty($sData['warehouse_id'])) $stock = WarehouseStock::get(['warehouse_id' => $sData['warehouse_id'], 'store_id' => $storeId]);
        if(!empty($stock))
        {
            $stock->save($sData);
        }
        else
        {
            $stock = WarehouseStock::create($sData);
        }
        return $stock;
    }
}